package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.eventbus.WebSocket;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.ui.activity.consult.JiuZhenFragment;
import com.hepinghospital.user.ui.activity.nursing.AppointNurseListActivity;
import com.hepinghospital.user.ui.activity.nursing.NurseConsultChatActivity;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.NurseConsultListResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/8/11 10:26
 */
public class NurseConsultListFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;

    MyAdapter adapter;
    List<NurseConsultListResponse.RecordsBran> list = new ArrayList<>();

    private static NurseConsultListFragment nurseConsultListFragment;


    public static NurseConsultListFragment newInstance() {
        if (nurseConsultListFragment == null) {
            nurseConsultListFragment = new NurseConsultListFragment();
        }
        return nurseConsultListFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_nurse_consult_list;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0));

    }

    @Override
    protected void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @OnClick({R.id.tv_consult})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_consult:
                ToastUtil.showToastCenter(mContext,"功能暂未开通");
//                startActivity(AppointNurseListActivity.class);
                break;
            default:
                break;
        }
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public MyAdapter.Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            MyAdapter.Holder myHolder;
            myHolder = new MyAdapter.Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_jz_nurse, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(MyAdapter.Holder holder, @SuppressLint("RecyclerView") int position) {
            holder.itemView.setOnClickListener(v -> {

                Intent intent = new Intent(mContext, NurseConsultChatActivity.class);
                intent.putExtra("diagnoseId", list.get(position).getDiagnoseId());
                mContext.startActivity(intent);
            });
            holder.itemView.setOnLongClickListener(v -> {
                if (list.get(position).getDoctorIsTop() == 0) {
                    new AlertDialog.Builder(mContext).setTitle(R.string.string_to_top)
                            .setMessage(R.string.string_to_top_content)
                            .setPositiveButton(R.string.string_confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 显示授权界面
                                    updateTop(list.get(position).getDiagnoseId(), 1 + "");
                                }
                            })
                            .setNegativeButton(R.string.string_cancel, null).show();
                } else {
                    new AlertDialog.Builder(mContext).setTitle(R.string.string_to_top)
                            .setMessage(R.string.string_to_top_content)
                            .setPositiveButton(R.string.string_confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 显示授权界面
                                    updateTop(list.get(position).getDiagnoseId(), 0 + "");
                                }
                            })
                            .setNegativeButton(R.string.string_cancel, null).show();
                }
                return false;
            });
            if (list.get(position).getDoctorIsTop() == 1) {
                holder.itemView.setBackgroundColor(Color.parseColor("#0F55B8A9"));
            } else {
                holder.itemView.setBackgroundColor(getResources().getColor(R.color.white));
            }
            holder.tv_name.setText(list.get(position).getDoctorName());
            holder.tv_department.setText(list.get(position).getDeptName());
            if (list.get(position).getMessageType() == 0) {
                holder.tv_message.setText(TextUtils.isEmpty(list.get(position).getContent()) ? getString(R.string.string_no_communication_records) : list.get(position).getContent());
            } else if (list.get(position).getMessageType() == 1) {
                holder.tv_message.setText(R.string.string_picture);
            } else if (list.get(position).getMessageType() == 6) {
                holder.tv_message.setText(R.string.string_prescription);
            } else if (list.get(position).getMessageType() == 2) {
                holder.tv_message.setText(R.string.string_voice);
            } else if (list.get(position).getMessageType() == -1) {
                holder.tv_message.setText(getString(R.string.string_no_communication_records));
            }
            holder.tv_time.setText(list.get(position).getSendTime());
            if (list.get(position).getUnreadCount() != 0) {
                holder.tv_unreadCount.setVisibility(View.VISIBLE);
                holder.tv_unreadCount.setText(list.get(position).getUnreadCount() + "");
            } else {
                holder.tv_unreadCount.setVisibility(View.GONE);
            }
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, list.get(position).getPicture(), holder.img_head);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_message, tv_time, tv_unreadCount, tv_consult_type;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_unreadCount = itemView.findViewById(R.id.tv_unreadCount);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_message = itemView.findViewById(R.id.tv_message);
                img_head = itemView.findViewById(R.id.img_head);
                tv_consult_type = itemView.findViewById(R.id.tv_consult_type);
            }
        }
    }

    public void queryNurseConsultList(int queryType) {
        RestProxy.getInstance().queryNurseConsultList(1, 100, new Observer<NurseConsultListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onNext(NurseConsultListResponse nurseConsultListResponse) {

                if (queryType == UIConstants.JIUZHEN_QUERY_TYPE_1) {
//                    if (nurseConsultListResponse.getRecords() != null && nurseConsultListResponse.getRecords().size() > 0) {
//                        JiuZhenFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_1, nurseConsultListResponse.getRecords().size());
//                        JiuZhenFragment.newInstance().jumpToPage(1);
//                    } else {
//                        JiuZhenFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_1, 0);
//
//                    }

                } else {
                    if (!UtilList.isEmpty(nurseConsultListResponse.getRecords())) {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.VISIBLE);
                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.GONE);
                        }
                        list.clear();
                        list.addAll(nurseConsultListResponse.getRecords());
                        adapter.notifyDataSetChanged();
                    } else {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.GONE);
                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.VISIBLE);
                        }
                    }
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh(false);
                }
            }

            @Override
            public void onComplete() {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh(true);
                }
            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
//            queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        } else {
//            System.out.println("不可见");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        if (webSocket.eventFlag == 0) {
            queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_109 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_101 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_110) {
            queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        }
    }

    private void updateTop(String diagnoseId, String status) {
        RestProxy.getInstance().updateTop(diagnoseId, status, new BaseObserver<String>() {
            @Override
            public void onSuccess(String s) {
                queryNurseConsultList(UIConstants.JIUZHEN_QUERY_TYPE_0);
            }
        });
    }
}